package com.xingfly.web;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.xingfly.model.Event;
import com.xingfly.model.Following;
import com.xingfly.model.Notification;
import com.xingfly.model.User;
import com.xingfly.repository.FollowingRepository;
import com.xingfly.security.jwt.annotation.CurrentUser;
import com.xingfly.service.*;
import com.xingfly.util.Type;
import com.xingfly.util.WebConstant;
import com.xingfly.web.model.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * Created by SuperS on 29/12/2016.
 */
@RestController
@RequestMapping("me")
public class MeController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private FollowService followService;
    @Autowired
    private PostService postService;
    @Autowired
    private EventService eventService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private FollowingRepository followingRepository;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private JwtService jwtService;


    @GetMapping
    public ResponseModel<User> me(@CurrentUser User user) {
        return ResponseModel.ok(user);
    }

    @PutMapping
    @Transactional
    public ResponseModel<User> update(@CurrentUser User user, @Param("password") String password, @Param("intro") String intro) {
        if (password != null) {
            user.setLastPasswordResetDate(new Date());
            user.setPassword(password);
            jwtService.delete(user.getId());
        }
        if (intro != null) {
            user.setIntro(intro);
        }
        accountService.save(user);
        return ResponseModel.ok(user);
    }

    @PutMapping("/avatar")
    @Transactional
    public ResponseModel<?> updateAvatar(@RequestParam("avatar") MultipartFile file, @CurrentUser User me) throws IOException {
        if (file.getSize() > WebConstant.FILE_MAX_SIZE) {
            return ResponseModel.error(HttpStatus.MULTI_STATUS, "超出文件大小");
        }
        if (file.isEmpty()) {
            return ResponseModel.error(HttpStatus.MULTI_STATUS, "文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!(suffixName.equals(".jpg") || suffixName.equals(".png") || suffixName.equals(".jpeg"))) {
            return ResponseModel.error(HttpStatus.MULTI_STATUS, "文件格式错误");
        }
        try {
            String path = "avatar/" + new Date().getTime() + "/" + me.getId() + "/" + fileName;
            Response response = uploadService.getUploadManager().put(file.getBytes(), path, uploadService.getUpToken());
            me.setAvatar(WebConstant.IMAGE_DOMAIN + "/" + path);
            return ResponseModel.create(response, HttpStatus.OK, "头像更新成功");
        } catch (QiniuException e) {
            Response response = e.response;
            return ResponseModel.create(response, HttpStatus.BAD_REQUEST, "上传失败");
        }


    }

    @GetMapping("/followers")
    public ResponseModel<?> myFollower(@CurrentUser User user) {
        return ResponseModel.create(followService.getFollowers(user.getId()), HttpStatus.OK);
    }

    @GetMapping("/following")
    public ResponseModel<?> myFollowing(@CurrentUser User user) {
        return ResponseModel.create(followService.getFollowingsByUserId(user.getId()), HttpStatus.OK);
    }

    @GetMapping("/posts")
    public ResponseModel<?> myPosts(@CurrentUser User user) {
        return ResponseModel.ok(postService.findPostsByUserId(user.getId()));
    }

    @DeleteMapping("/following/{id}")
    @Transactional
    public ResponseModel<?> unFollowing(@CurrentUser User user, @PathVariable("id") Long id) {
        User followingUser = accountService.find(id);
        if (followingUser == null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户不存在!");
        }
        if (followService.isFollowing(user.getId(), followingUser.getId())) {
            //获取事件
            Event event = eventService.getEvent(Type.OBJECT_TYPE_FOLLOWING, followingRepository.findByUserIdAndFollowingUserId(user.getId(), id).getId());
            //取消关注
            followService.unFollowing(user.getId(), followingUser.getId());
            //取消提醒
            notificationService.deleteNotify(event.getId(), user.getId(), id);
            //删除事件
            eventService.delete(event);
        } else {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "未关注该用户!");
        }
        return ResponseModel.create(null, HttpStatus.OK, "取消关注成功!");
    }

    @PostMapping("/following/{id}")
    @Transactional
    public ResponseModel<?> following(@CurrentUser User user, @PathVariable("id") Long id) {
        User followingUser = accountService.find(id);
        if (followingUser == null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户不存在!");
        }
        if (Objects.equals(user.getId(), followingUser.getId())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "不能关注自己哦!");
        }

        if (followService.isFollowing(user.getId(), followingUser.getId())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "已关注该用户");
        } else {
            followService.followingUser(user.getId(), followingUser.getId());
            Following following = followingRepository.findByUserIdAndFollowingUserId(user.getId(), id);
            Event event = eventService.create(Type.OBJECT_TYPE_FOLLOWING, following);
            Notification notification = new Notification(Type.NOTIFY_TYPE_FOLLOW, 0L, event, followingUser, user, Type.UNREAD);
            notificationService.doNotify(notification);
        }
        return ResponseModel.create(null, HttpStatus.OK, "关注成功!");
    }
}
